package com.uit.ecommerce.servletsservice;

import com.uit.ecommerce.dto.GlobalWeatherDTO;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.ws.WebServiceRef;
import net.webservicex.GlobalWeather;
import net.webservicex.GlobalWeatherSoap;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 *
 * @author ngloc_it
 */
@WebServlet(name="WouldWeatherServlet", urlPatterns={"/WouldWeatherServlet"})
public class WouldWeatherServlet extends HttpServlet {
    @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/www.webservicex.net/globalweather.asmx.wsdl")
    private GlobalWeather service;    
   

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
       
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        HttpSession seesion = req.getSession();
        PrintWriter out = resp.getWriter();

        String function = (String)req.getParameter("function");
        String country = (String)req.getParameter("country");
        String city = (String) req.getParameter("city");

        if(function != null){
            if(function.equalsIgnoreCase("updatecity")){
                UpdateCity(country, resp);
                return;
            }else if(function.equalsIgnoreCase("loadweather")){
                if((city != null) && (country != null)){
                    LoadWeather(country, city, resp);
                    return;
                }
            }else{
                ArrayList<String> listCountry = GetAllCountry();
                if(listCountry != null)
                    seesion.setAttribute("listcountry", listCountry);
            }
        }

//        if(listCity != null){
//            for(int i = 0; i < listCity.size(); i++){
//                out.println((i+1) + listCity.get(i));
//            }
//        }

        String path = "./jsps/ThoiTietTheGioi.jsp";
        resp.sendRedirect(path);
    }

    /**
     * Get all country whichs service support
     * @return
     */
    private ArrayList<String> GetAllCountry(){
        GlobalWeatherSoap port = service.getGlobalWeatherSoap();
        String xmlData = port.getCitiesByCountry("");
        ArrayList<String> countries = ParseXML(xmlData, "Country");
        if(countries != null){
            int n = countries.size();
            int i, j;
            for(i = 0; i < n-1; i++){
                String temp = countries.get(i);
                for(j = i+1; j < n; j++){
                    if(temp.equals(countries.get(j))){
                        countries.remove(j);
                        n--;
                        j--;
                    }
                }
            }
        }
        return countries;
    }


    /**
     * Get all city in a country
     * @param countryName which country
     * @return list city of countryName
     */
    public ArrayList<String> GetCityByCountry(String countryName){
        ArrayList<String> listResult = new ArrayList<String>();
        GlobalWeatherSoap port = service.getGlobalWeatherSoap();
        
        String xmlRecord = port.getCitiesByCountry(countryName);
        listResult = ParseXML(xmlRecord, "City");

        return listResult;
    }

    public static String getCharacterDataFromElement(Element e) {
        Node child = e.getFirstChild();
        if (child instanceof CharacterData) {
            CharacterData cd = (CharacterData) child;
            return cd.getData();
        }
        return "?";
    }

    public ArrayList<String> ParseXML(String xmlData, String xmlTab){
        ArrayList<String> datas = new ArrayList<String>();

         try {
            DocumentBuilderFactory dbf =
                DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xmlData));

            Document doc = db.parse(is);
            NodeList nodes = doc.getElementsByTagName(xmlTab);

            //
            for (int i = 0; i < nodes.getLength(); i++) {
               Element element = (Element) nodes.item(i);
               String cityName = getCharacterDataFromElement(element);
               datas.add(cityName);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return datas;
    }
 
    public GlobalWeatherDTO ParseXML(String xmlData){
        GlobalWeatherDTO gData = new GlobalWeatherDTO();
        try {
            DocumentBuilderFactory dbf =
                DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xmlData));

            Document doc = db.parse(is);

            String[] xmlTab = {GlobalWeatherDTO.TAB_Location, GlobalWeatherDTO.TAB_Time,
                GlobalWeatherDTO.TAB_Wind, GlobalWeatherDTO.TAB_Visibility,
                GlobalWeatherDTO.TAB_SkyConditions, GlobalWeatherDTO.TAB_Temperature,
                GlobalWeatherDTO.TAB_DewPoint, GlobalWeatherDTO.TAB_RelativeHumidity,
                GlobalWeatherDTO.TAB_Pressure, GlobalWeatherDTO.TAB_Status};

            ArrayList<String> listTemp = new ArrayList<String>();
            NodeList nodes;
            int i;
            for(i = 0; i < xmlTab.length; i++){
                nodes = doc.getElementsByTagName(xmlTab[i]);
                Element ele = (Element) nodes.item(0);
                String strTem = getCharacterDataFromElement(ele);
                listTemp.add(strTem);
            }
            i = 0;
            gData.setLocation(listTemp.get(i++));
            gData.setTime(listTemp.get(i++));
            gData.setWind(listTemp.get(i++));
            gData.setWindVisiblity(listTemp.get(i++));
            gData.setSkyCondition(listTemp.get(i++));
            gData.setTemperature(listTemp.get(i++));
            gData.setDewPoint(listTemp.get(i++));
            gData.setRelativeHumidity(listTemp.get(i++));
            gData.setPressure(listTemp.get(i++));
            gData.setStatus(listTemp.get(i));
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return gData;
    }

    private void UpdateCity(String country, HttpServletResponse resp) throws IOException {
        PrintWriter out = resp.getWriter();

        ArrayList<String> cities = GetCityByCountry(country);
        if(cities == null)
            return;
      
        int n = cities.size();
        
        out.println("<select>");
        for(int i = 0; i < n; i++){
            out.println("<option>"+ cities.get(i) +"</option>");
        }
        out.println("</select>");
    }


    private void LoadWeather(String country, String city, HttpServletResponse resp) throws IOException {
        PrintWriter out = resp.getWriter();
        GlobalWeatherSoap port = service.getGlobalWeatherSoap();
        GlobalWeatherDTO gData = new GlobalWeatherDTO();

        String xmlData = port.getWeather(city, country);
        if(xmlData == null)
            return;

//        ArrayList<String> extract =  ParseXML(xmlData, "string");
//        if(extract != null) {
//            if(extract.get(0).equalsIgnoreCase("Data Not Found"))
//                return;
//        }

        gData = ParseXML(xmlData);

        if(gData != null){
            out.println("<table>");            
            out.println("<tr><th colspan='3'>" + gData.getLocation() + "<br/>" + gData.getTime() + "</th></tr>");
            out.println("<tr><td colspan='3'>" + "<b>Wind:</b> " + gData.getWind() + "<br/>"
                        + "<b>Win vidiblity:</b> " + gData.getWindVisiblity() + "<br/>"
                        + "<b>Temperature: </b>" + gData.getTemperature() + "<br/>"
                        + "<b>RelativeHumidity:</b> " + gData.getRelativeHumidity() + "<br/>"
                        + "<b>Pressure:</b> " + gData.getPressure() + "</td></tr>");            
            out.println("</table>");

//            <table id="tableinfo">
//                    <tr><th>Chỉ số</th><th>Giá trị</th><th>Ghi chú</th></tr>
//                    <tr><td>Nhiệt độ thấp nhất</td><td>15</td><td>No thing</td></tr>
//                    <tr><td>Nhiệt độ cao nhất</td><td>15</td><td>No thing</td></tr>
//                    <tr><td>Độ ẩm</td><td>50%</td><td>No thing</td></tr>
//                </table>
        }
    }
}
